# -*- coding: utf-8 -*-

from rest_framework import serializers
from core.serializers import CustomModelSerializer
from core.relations import BaseNameWritableRelatedField, UserNameWritableRelatedField
from apps.pms.models import Requirement, Version
from apps.sys.models import DictData
from .models import Bug, BugOperate, BugComment


class BugSerializer(CustomModelSerializer):
    """
    缺陷管理-序列化器
    """

    product = BaseNameWritableRelatedField()
    version = BaseNameWritableRelatedField()
    resolved_version = BaseNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )
    module = BaseNameWritableRelatedField()
    towner = UserNameWritableRelatedField()
    downer = UserNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )
    tcs = BaseNameWritableRelatedField(many=True)
    related_bugs = BaseNameWritableRelatedField(
        many=True, required=False, allow_empty=True, allow_null=True
    )

    reqs = serializers.SerializerMethodField()
    activations = serializers.SerializerMethodField()
    resolved_type = serializers.SerializerMethodField()

    def get_reqs(self, instance):
        related_reqs = set()
        for related_case in instance.tcs.all():
            for related_req in related_case.reqs.all():
                related_reqs.add(related_req)
        related_reqs_serializer = BugRequirementSerializer(related_reqs, many=True)
        return related_reqs_serializer.data

    def get_activations(self, instance):
        return BugOperate.objects.filter(bug=instance.id, operation="ACTIVATE").count()

    def get_resolved_type(self, instance):
        bug_operate = BugOperate.objects.filter(
            bug=instance.id, operation="RESOLVE"
        ).order_by('-update_time').first()
        return bug_operate.extras.get("resolved_type") if bug_operate else None

    class Meta:
        model = Bug
        fields = "__all__"
        read_only_fields = ["id"]


class BugRequirementSerializer(CustomModelSerializer):
    """
    关联需求-序列化器
    """

    class Meta:
        model = Requirement
        fields = ("id", "name")


class BugTreeSelectSerializer(CustomModelSerializer):
    """
    缺陷管理-树型菜单序列化器
    """

    name = serializers.SerializerMethodField(read_only=True)
    type = serializers.SerializerMethodField(read_only=True)

    def get_name(self, instance):
        status_lable = DictData.objects.get(
            type="tms_bug_status", value=instance.status
        ).label
        return f"【{status_lable}】{instance.name}"

    def get_type(self, instance):
        return instance._meta.object_name

    class Meta:
        model = Requirement
        fields = ["id", "name", "parent", "type"]
        read_only_fields = ["id"]


class BugOperateSerializer(CustomModelSerializer):
    """
    缺陷操作管理-序列化器
    """

    extras = serializers.SerializerMethodField()

    def get_extras(self, instance):
        if instance.operation == "RESOLVE":
            resolved_type = instance.extras.get("resolved_type")
            resolved_version = instance.extras.get("resolved_version")
            if resolved_type and resolved_version:
                resolved_type = DictData.objects.get(
                    type="tms_bug_resolved_type", value=resolved_type
                ).label
                resolved_version = Version.objects.get(id=resolved_version).name
            return {
                "resolved_type": resolved_type,
                "resolved_version": resolved_version,
            }
        else:
            return instance.extras

    class Meta:
        model = BugOperate
        fields = "__all__"
        read_only_fields = ["id"]


class BugOperateCreateAndUpdateSerializer(CustomModelSerializer):
    """
    缺陷操作管理-序列化器
    """

    class Meta:
        model = BugOperate
        fields = "__all__"
        read_only_fields = ["id"]


class BugCommentSerializer(CustomModelSerializer):
    """
    缺陷评论管理-序列化器
    """

    class Meta:
        model = BugComment
        fields = "__all__"
        read_only_fields = ["id"]
